import 'dart:io';

import 'package:app/routes/app_pages.dart';
import 'package:business_boost/bridge/boost_bridge.dart';
import 'package:business_boost/bridge/boost_bridge_impl.dart';
import 'package:business_getx/business_getx.dart';
import 'package:business_user/bridge/user_bridge.dart';
import 'package:business_user/bridge/user_bridge_impl.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ume_kit_console_plus/flutter_ume_kit_console_plus.dart';
import 'package:flutter_ume_kit_device_plus/flutter_ume_kit_device_plus.dart';
import 'package:flutter_ume_kit_dio_plus/flutter_ume_kit_dio_plus.dart';
import 'package:flutter_ume_kit_perf_plus/flutter_ume_kit_perf_plus.dart';
import 'package:flutter_ume_kit_show_code_plus/flutter_ume_kit_show_code_plus.dart';
import 'package:flutter_ume_kit_ui_plus/flutter_ume_kit_ui_plus.dart';
import 'package:flutter_ume_plus/flutter_ume_plus.dart';
import 'package:lib_core/boost/boost_binding.dart';
import 'package:lib_core/bridge/common_bridge.dart';
import 'package:lib_core/lib_core.dart';
import 'package:lib_core/net/dio_client.dart';
import 'package:lib_core/utils/log.dart';
import 'package:lib_ui/bridge/dialog_bridge.dart';
import 'package:lib_ui/bridge/dialog_bridge_impl.dart';
import 'package:lib_ui/common/theme/theme_controller.dart';
import 'package:lib_ui/gen/colors.gen.dart';
import 'package:lib_ui/widget/env_widget.dart';

void startApp(List<String>? args) {
  GlobalCst.isLibrary = false;
  main(args);
}

void main(List<String>? args) async {
  BoostBinding();
  await init();
  // PageVisibilityBinding.instance.addGlobalObserver(AppLifecycleObserver());
  initChannel();
  // 沉浸式状态栏
  if (!GlobalCst.isLibrary && Platform.isAndroid) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(statusBarColor: Colors.transparent, statusBarIconBrightness: Brightness.dark));
  }
}

void initChannel() {
  // 初始化channel
  CommonFlutterApi.setup(CommonBridgeImpl());
  DialogFlutterApi.setup(DialogBridgeImpl());
  UserFlutterApi.setup(UserBridgeImpl());
  BoostFlutterApi.setup(BoostBridgeImpl());
}

Future<void> init() async {
  await Log.init();
  await GetStorage.init();
  // 网络框架初始化
  DioClient().init();
  // 初始化插件，用于平台与原生之间通讯
  await Get.putAsync(() => AuthService().init());
  // 初始化字节跳动
  if (kDebugMode) {
    PluginManager.instance
      ..register(const WidgetInfoInspector())
      ..register(const WidgetDetailInspector())
      ..register(const ColorSucker())
      ..register(AlignRuler())
      ..register(const ColorPicker()) // 新插件
      ..register(const TouchIndicator()) // 新插件
      ..register(Performance())
      ..register(const ShowCode())
      ..register(const MemoryInfoPage())
      ..register(CpuInfoPage())
      ..register(const DeviceInfoPanel())
      ..register(Console())
      ..register(DioInspector(dio: DioClient.dio));
    runApp(UMEWidget(enable: true, child: App()));
  } else {
    runApp(App());
  }
}

class OtherApp extends StatefulWidget {
  const OtherApp({super.key});

  @override
  State<OtherApp> createState() => _OtherAppState();
}

class _OtherAppState extends State<OtherApp> {
  final _themeController = Get.put(ThemeController());

  Route<dynamic>? routeFactory(RouteSettings settings, String? uniqueId) {
    FlutterBoostRouteFactory? func = AppPages.routers[settings.name];
    return FlutterSmartDialog.boostMonitor(func?.call(settings, uniqueId));
  }


  @override
  Widget build(BuildContext context) {
    return FlutterBoostApp(
      routeFactory,
      appBuilder: (home) {
        return GetMaterialApp(
          home: home,
          // 国际化
          localizationsDelegates: const [
            GlobalMaterialLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          translations: AppTranslation(),
          locale: const Locale('zh', 'CN'),
          // 默认语言
          supportedLocales: const [Locale('zh', 'CN'), Locale('en', 'US')],
          // 支持语言
          localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) {
            return locale;
          },
          theme: _themeController.currentTheme,
          builder: (context, child) {
            return GestureDetector(
              onTap: () => hideKeyboard(context),
              child: Stack(
                children: [
                  FlutterSmartDialog.init()(context, child),
                  if (!GlobalCst.isLibrary) const EnvWidget(),
                ],
              ),
            );
          },
        );
      },
    );
  }

  void hideKeyboard(BuildContext context) {
    FocusScopeNode curFocus = FocusScope.of(context);
    if (!curFocus.hasPrimaryFocus && curFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }
}

class App extends BoostApp {
  @override
  Map<String, FlutterBoostRouteFactory> routes = AppPages.routers;
  final _themeController = Get.put(ThemeController());

  @override
  Widget appBuilder(BuildContext context, Widget home) {
    return GetMaterialApp(
      home: home,
      // 国际化
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      translations: AppTranslation(),
      locale: const Locale('zh', 'CN'),
      // 默认语言
      supportedLocales: const [Locale('zh', 'CN'), Locale('en', 'US')],
      // 支持语言
      localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) {
        return locale;
      },
      theme: _themeController.currentTheme,
      builder: (context, child) {
        return GestureDetector(
          onTap: () => hideKeyboard(context),
          child: Stack(
            children: [
              FlutterSmartDialog.init()(context, child),
              if (!GlobalCst.isLibrary) const EnvWidget(),
            ],
          ),
        );
      },
    );
  }

  void hideKeyboard(BuildContext context) {
    FocusScopeNode curFocus = FocusScope.of(context);
    if (!curFocus.hasPrimaryFocus && curFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }
}
